package com.springboot.demo.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.LockSupport;

/**
 * 自定义FutureTask
 *
 * @author supu
 * @date 2020-03-25 16:39
 **/
public class CustomFutureTask<T> implements Runnable {
    Callable<T> callable;

    T result;

    // 开始状态 0，结束状态 1
    private volatile int state = 0;

    private BlockingQueue<Thread> blockingQueue = new LinkedBlockingQueue<>();

    public CustomFutureTask(Callable<T> callable) {
        this.callable = callable;
    }

    @Override
    public void run() {
        try {
            result = callable.call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            state = 1;
        }

        Thread thread = blockingQueue.poll();
        while (thread != null) {
            LockSupport.unpark(thread);
            thread = blockingQueue.poll();
        }
    }

    public T get() {
        if (state == 1) {
            return result;
        }

        // 阻塞线程，等待执行结果处理完
        while (state != 1) {
            blockingQueue.offer(Thread.currentThread());
            LockSupport.park();
        }
        return result;
    }
}
